/*
 * Copyright (C) 2015
 * All rights reserved.
 *
 * $$File: $$
 * $$DateTime: $$
 * $$Author: $$
 * $$Revision: $$
 */

package com.glela.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.glela.common.exception.BusinessError;
import com.glela.common.exception.BusinessException;
 
/**
 * 类描述：
 * 
 * 
 */
public class PostStreamUtil
{
	private static final String CRNL = System.getProperty("line.separator");
	final static Logger logger = LoggerFactory.getLogger(PostStreamUtil.class);
 
	/**
	 * 方法描述：
	 * 
	 * @param 5302
	 * 
	 */
	public static void main(String[] args)
	{
		//订购流量接口
//		String iAddress = "http://test.dahanfc.com:3429/if/FCOrderServlet";
//		Map<String, String> map = new HashMap<String, String>();
//		String timestamp = System.currentTimeMillis() + "";
//		String account = "AdminShshz";
//		String mobiles = "18521081321";
//		String sing = MD5.MD5Encode(account + MD5.MD5Encode("111111") + timestamp + mobiles);
//		map.put("timestamp", timestamp);
//		map.put("account", account);
//		map.put("mobiles", mobiles);
//		map.put("sign", sing);
//		//		map.put("packageSize", "100");
//		//{"id":"000000004d375387014d41da22a8002f","name":"联通全国200M","totalSize":200,"yysType":2,"flowType":1}
//		map.put("unicomProductId", "000000004d375387014d41da22a8002f");
//		String jsonResult = JsonUtil.simpleMapToJsonStr(map);
//		System.out.println(jsonResult);
//		PostStreamUtil.sendPostStreamHandler(jsonResult, iAddress);

		//订购话费接口
		//		String iAddress = "http://test.dahanfc.com:3429/if/FCPhoneBillOrderServlet";
		//		Map<String, String> map = new HashMap<String, String>();
		//		String timestamp = System.currentTimeMillis() + "";
		//		String account = "AdminShshz";
		//		String mobiles = "18521081321";
		//		String sing = MD5.MD5Encode(account + MD5.MD5Encode("test5370") + timestamp + mobiles);
		//		map.put("timestamp", timestamp);
		//		map.put("account", account);
		//		map.put("mobiles", mobiles);
		//		map.put("sign", sing);
		//		map.put("price", "20");
		//		String jsonResult = JsonUtil.simpleMapToJsonStr(map);
		//		System.out.println(jsonResult);

		//		PostStreamUtil.sendPostStreamHandler(jsonResult, iAddress);

		//查询可订购产品接口
		//		String iAddress = "http://test.dahanfc.com:3429/if/FCSearchProductServlet";
		//		String account = "account=AdminShshz";
		//		PostStreamUtil.sendPostStreamHandler(account, iAddress);

		//状态报告查询接口
		//		String iAddress = "http://test.dahanfc.com:3429/if/FCSearchReportDataServlet";
		//		String account = "account=AdminShshz";
		//		PostStreamUtil.sendPostStreamHandler(account, iAddress);

		//余额查询接口
//				String iAddress = "http://if.dahanbank.cn/FCQueryBalanceServlet";//"http://test.dahanfc.com:3429/if/FCQueryBalanceServlet";
//				String account = "rndtest";//PropsUtil.getString(prop, key);
//				String sign = MD5.MD5Encode(account + MD5.MD5Encode("rndtest123"));
//				String iCommString = "account=" + account + "&sign=" + sign;
//				PostStreamUtil.sendPostStreamHandler(iCommString, iAddress);

		//短信通知模板查询接口
		//		String iAddress = "http://test.dahanfc.com:3429/if/FCMsgTemplateServlet";
		//		String account = "AdminShshz";
		//		String sign = MD5.MD5Encode(account + MD5.MD5Encode("test5370"));
		//		String iCommString = "account=" + account + "&sign=" + sign;
		//		PostStreamUtil.sendPostStreamHandler(iCommString, iAddress);

		//2.8.	密码修改接口
		//		String iAddress = "http://test.dahanfc.com:3429/if/FCModifyPwdServlet";
		//		String account = "AdminShshz";
		//		String sign = MD5.MD5Encode(account + MD5.MD5Encode("test5370"));
		//		String newPwd = "test8888";
		//		String iCommString = "account=" + account + "&sign=" + sign + "&newPwd=" + newPwd;
		//		PostStreamUtil.sendPostStreamHandler(iCommString, iAddress);

		//2.9.	归属地查询接口
		//		String iAddress = "http://test.dahanfc.com:3429/if/FCGetAttribution";
		//		String mobile = "18521081321";
		//		String iCommString = "mobile=" + mobile;
		//		PostStreamUtil.sendPostStreamHandler(iCommString, iAddress);
		//		System.out.println(System.getProperty("line.separator"));
		//		PostStreamUtil.sendStatusReport();
		//回调
		sendStatusReport();
	}

	/**
	 * 方法描述：使用post请求发送数据包到指定地址
	 * 
	 * @param iCommString
	 * @param iAddress
	 * @return
	 * @author: liujie
	 * @throws BusinessException 
	 * 
	 */
	public static String sendPostStreamHandler(String iCommString, String iAddress) throws BusinessException
	{
		String _oRecString = "";
		URL _url = null;
		HttpURLConnection _urlConn = null;
		OutputStream _out = null;
		InputStreamReader _isr = null;
		InputStream _is = null;
		BufferedReader _br = null;
		try {
			_url = new URL(iAddress); // 根据数据的发送地址构建URL
			_urlConn = (HttpURLConnection) _url.openConnection(); // 打开链接
			_urlConn.setConnectTimeout(30000); // 链接超时设置为30秒
			_urlConn.setReadTimeout(30000); // 读取超时设置30秒
			_urlConn.setRequestMethod("POST"); // 链接相应方式为post
			_urlConn.setDoOutput(true);
			_urlConn.setDoInput(true);

			_out = _urlConn.getOutputStream();
			_out.write(iCommString.getBytes("utf-8"));
			_out.flush();

			_is = _urlConn.getInputStream();
			_isr = new InputStreamReader(_is, "UTF-8");
			_br = new BufferedReader(_isr);
			StringBuffer _tempSB = new StringBuffer();
			String _tempStr = null;
			while ((_tempStr = _br.readLine()) != null) {
				_tempSB.append(_tempStr + CRNL);
			}
			_oRecString = _tempSB.toString().trim();
			System.out.println("路由到" + iAddress + "?" + iCommString + "成功，返回：" + _oRecString);
		}
		catch (Exception e) {
			logger.error("PostStreamUtil。sendPostStreamHandler 失败！！" + e);
 			_oRecString = "-107";
 			throw new BusinessException(BusinessError.C9999,"API调用失败");
 		}
		finally {
			try {
				if (_out != null) {
					_out.close();
				}
				if (_br != null) {
					_br.close();
				}
				if (_isr != null) {
					_isr.close();
				}
				if (_is != null) {
					_is.close();
				}

			}
			catch (IOException e) {
				e.printStackTrace();
			}
			if (_urlConn != null) {
				_urlConn.disconnect();
			}
		}
		return _oRecString;
	}

	private static void sendStatusReport()
	{
		HttpClient client = new HttpClient();
		String address = "http://localhost:8080/yg-c-platform/reportReceiveHttpCtrl";
		PostMethod postMethod = new PostMethod(address);
		postMethod.getParams().setContentCharset("UTF-8");
		//{"clientOrderId":"20160602000002","mobile":"13764322841","reportTime":"June 02, 2016 4:46:04 PM","status":0,"errorCode":"","errorDesc":""};
		String _info = "{\"clientOrderId\":\"20160602000002\",\"mobile\":\"13764322841\",\"reportTime\":\"June 02, 2016 4:46:04 PM\",\"status\":1,\"errorCode\":\"\",\"errorDesc\":\"\"}";
				//"{\"clientOrderId\":\"20160602000002\",\"mobile\":\"13764322841\",\"reportTime\":\"June 06, 2016 2:33:44 PM\",\"status\":0,\"errorCode\":\"\",\"errorDesc\":\"\"}";
		postMethod.setRequestBody(_info);
		HttpMethod httpMethod = postMethod;
		try {
			client.executeMethod(httpMethod);
			String _resp = httpMethod.getResponseBodyAsString();
			httpMethod.releaseConnection();
			System.out.println(_resp);
		}
		catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private PostStreamUtil()
	{
	}
}
